//
//  main.m
//  OC04_Homework
//
//  Created by dllo on 16/7/7.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Color.h"
int main(int argc, const char * argv[]) {

    NSString *path = @"/Users/dllo/DLS160710/Objective-C/HomeWork/OC04_Homework/crayons.txt";
    NSString *sourceStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    // 通过\n把字符串转换为数组
    NSArray *sourceArr = [sourceStr componentsSeparatedByString:@"\n"];
    // 通过  #分割后的数组初始化
    NSArray *keysValuesArr = [NSArray array];
    // 声明存储颜色的字典
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSMutableDictionary *newDic = [NSMutableDictionary dictionary];
#pragma mark - forin
//    for (NSString *str in sourceArr) {
//        keysValuesArr = [str componentsSeparatedByString:@" #"];
//        if (keysValuesArr.count == 2) {
//            [dic setObject:sourceArr.lastObject forKey:sourceArr.firstObject];
//            Color *color = [Color colorWithName:keysValuesArr[0] colorValue:keysValuesArr[1]];
//            NSMutableArray *valuesArr = [newDic objectForKey:[color.name substringToIndex:1]];
//
//            if (!valuesArr) {
//                valuesArr = [NSMutableArray array];
//                [valuesArr addObject:color];
//                [newDic setObject:valuesArr forKey:[color.name substringToIndex:1]];
//            } else {
//                [valuesArr addObject:color];
//            }
//        }
//    }
#pragma mark - for循环
    for (int i = 0; i < sourceArr.count; i++) {
        if ([sourceArr[i] length] > 0) {
            keysValuesArr = [sourceArr[i] componentsSeparatedByString:@" #"];
            [dic setObject:keysValuesArr.lastObject forKey:keysValuesArr.firstObject];
        }
    }
    
    NSArray *allKeys = dic.allKeys;
    for (int i = 0; i < allKeys.count; i++) {
        // 取首字母
        NSString *subString = [allKeys[i] substringToIndex:1];
        // 通过首字母在新的字典取出对应的数组
        NSMutableArray *colorArray = [newDic objectForKey:subString];
        Color *newColor = [Color colorWithName:allKeys[i] colorValue:[dic objectForKey:allKeys[i]]];
        // 如果数组不存在
        if (colorArray == nil) {
            colorArray = [NSMutableArray array];
            [colorArray addObject:newColor];
            [newDic setObject:colorArray forKey:subString];
        } else {
            [colorArray addObject:newColor];
        }
    }
    NSLog(@"%@", newDic);
    return 0;
}
